<?php
/**
 * User: b179a9
 * Date: 10/13/11
 * Time: 5:25 PM
 */

namespace Managers;

class Invites extends BaseManager
{

    const TABLE = '\Catalog\Invites';

    public function getByToken($token)
    {
        $params = explode('|', $token);

        if(count($params) != 2) {
            throw new \Exception('Invalid invite token.');
        }

        $id = $params[0];
        $sign = $params[1];

        $res = $this->_em->createQueryBuilder()
                ->select('i,u')
                ->from(self::TABLE, 'i')
                ->join('i.user', 'u')
                ->where('i.id = :id')
                ->setParameter('id', $id)
                ->getQuery()
                ->getArrayResult();
        
        if (count($res) == 0) {
            throw new \Exception('Invite does not exist.');
        }
        $invite = $res[0];
        if(Users::getSecretWord($invite['id'], $invite['email']) != $sign){
            throw new \Exception('Invalid invite sign.');
        }

        return $invite;
    }

    public function add($user_id, array $params) {

        $invite = new \Catalog\Invites();

        $invite->setEmail($params['email']);
        $user = $this->_em->getReference(Users::TABLE, $user_id);
        $invite->setUser($user);
        $invite->setHash(Users::getSecretWord($user_id, $params['email']));

        $this->_em->persist($invite);
        $this->_em->flush();
        return $invite;
    }

}
